package com.developer.datastorage.activity;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.developer.datastorage.R;
import com.developer.datastorage.util.Util;

public class SharedPrefSaveActivity extends AbstractActivity {

	private static final String FILE_NAME = "names";
	private static final String USER_NAME = "user_name";
	private static final String PASSWORD = "password";
	private static final String DEFAULT_VALUE = "N/A";

	private EditText txtUserName;
	private EditText txtPassword;
	private Button btnSave;
	private Button btnLoad;

	@Override
	public void setLayout() {
		setContentView(R.layout.activity_shared_pref);
	}

	@Override
	public void initializeComponents() {
		txtUserName = (EditText) findViewById(R.id.txt_shared_pref_username);
		txtPassword = (EditText) findViewById(R.id.txt_shared_pref_password);
		btnSave = (Button) findViewById(R.id.btn_shared_pref_save);
		btnLoad = (Button) findViewById(R.id.btn_shared_pref_load);
	}

	@Override
	public void registerEvents() {
		btnSave.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				String name = txtUserName.getText().toString();
				String password = txtPassword.getText().toString();
				SharedPreferences preferences = getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
				Editor editor = preferences.edit();
				editor.putString(USER_NAME, name);
				editor.putString(PASSWORD, password);
				editor.commit();
				Util.showMessage(SharedPrefSaveActivity.this, "Values saved.");
			}
		});
		btnLoad.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				SharedPreferences preferences = getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
				String username = preferences.getString(USER_NAME, DEFAULT_VALUE);
				String password = preferences.getString(PASSWORD, DEFAULT_VALUE);
				Util.showMessage(SharedPrefSaveActivity.this, "User name: " + username + ", Password: " + password);
			}
		});
	}

}
